<template>
  <view class="add-new-supplier">
    <view class="header-right" @click="visible = true">
      <text class="iconfont ve-icon-add" style="font-size: 36rpx; margin-right: 8rpx"></text>
      {{ buttonText }}
    </view>
    <!-- 新增弹窗 -->
    <ve-modal :title="buttonText" v-model="visible" cancelText="取消" @confirm="onConfirm" @close="onClose" :okLoading="okLoading">
      <ve-form ref="formRef" :model="form" :rules="rules">
        <ve-form-item label="供应商类型"> {{ supplierTypeName }} </ve-form-item>
        <ve-form-item label="供应商名称" prop="supplierName" required>
          <ve-input v-model="form.supplierName" maxlength="30" placeholder="请输入" />
        </ve-form-item>
      </ve-form>
    </ve-modal>
  </view>
</template>
<script setup>
  import { ref, computed } from 'vue'
  import { supplierSave } from '@/api/market/supplier'
  const props = defineProps({
    config: {
      type: Object,
      default: () => {},
    },
  })
  const emits = defineEmits(['success'])
  // 字典数据
  const supplierTypeEnum = {
    0: '维修',
    1: '保养',
    6: '年检厂',
    7: '保险公司',
  }
  // 供应商类型id
  const supplierType = props.config.supplierType
  const supplierTypeName = supplierTypeEnum[supplierType]

  // button标题
  const buttonText = computed(() => {
    return '新增供应商'
  })

  // 新增供应商
  const visible = ref(false)

  const form = ref({
    supplierName: '',
    supplierType,
  })
  const rules = ref({
    supplierName: {
      required: true,
      message: '请输入供应商名称',
    },
  })

  const onClose = () => {
    visible.value = false
    form.value.supplierName = ''
    okLoading.value = false
  }

  const formRef = ref(null)
  const okLoading = ref(false)
  const onConfirm = () => {
    formRef.value.validate((valid) => {
      if (valid) {
        okLoading.value = true
        supplierSave(form.value)
          .then((res) => {
            visible.value = false
            form.value.supplierName = ''
            uni.showToast({
              icon: 'none',
              title: '操作成功',
            })
            emits('success')
          })
          .finally(() => {
            okLoading.value = false
          })
      }
    })
  }
</script>
<style lang="scss" scoped>
  .add-new-supplier {
    line-height: 1;
    .header-right {
      display: flex;
      align-items: center;
      font-size: 30rpx;
      font-weight: 400;
      color: #165dff;

      .svg-icon {
        margin-right: 8rpx;
      }
    }
  }
</style>
